package controller

import (
	"sale-admin/internal/app/web/schema"
	"sale-admin/internal/app/web/service/goods"
	"sale-admin/internal/app/web/service/robot"
	"sale-admin/internal/define"
	"sort"
	"strings"

	"192.168.1.75/go-pkg/errorx"
	"192.168.1.75/go-pkg/response"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
)

type Goods struct{}

// AddCornerLabel 新增角标
func (g Goods) AddCornerLabel(c *gin.Context) {
	var params struct {
		ID        string `json:"id"`
		Name      string `json:"name"`
		Image     string `json:"image"`
		Position  int    `json:"position"`
		Type      int    `json:"type"`
		StartTime int    `json:"start_time"`
		EndTime   int    `json:"end_time"`
	}
	err := c.ShouldBindWith(&params, binding.JSON)
	if err != nil {
		response.JSON(c, nil, errorx.New("参数错误", -1))
		return
	}
	err = robot.RobotCornerLabel{}.Add(
		c.Request.Context(),
		params.ID,
		params.Image,
		params.Name,
		params.Position,
		params.Type,
		params.StartTime,
		params.EndTime,
	)
	response.JSON(c, nil, err)
}

// DelCornerLabel 删除角标
func (g Goods) DelCornerLabel(c *gin.Context) {
	var params struct {
		ID string `json:"id"`
	}
	err := c.ShouldBindWith(&params, binding.JSON)
	if err != nil {
		response.JSON(c, nil, errorx.New("参数错误", -1))
		return
	}
	err = robot.RobotCornerLabel{}.Del(
		c.Request.Context(),
		params.ID,
	)
	response.JSON(c, nil, err)
}

// ListCornerLabel 角标列表
func (g Goods) ListCornerLabel(c *gin.Context) {
	var params struct {
		Page   int    `json:"page"`
		Limit  int    `json:"limit"`
		Type   int    `json:"type"`
		Name   string `json:"name"`
		Status int    `json:"status"`
	}
	err := c.ShouldBindWith(&params, binding.JSON)
	if err != nil {
		response.JSON(c, nil, errorx.New("参数错误", -1))
		return
	}
	list, count, err := robot.RobotCornerLabel{}.List(
		c.Request.Context(),
		params.Page,
		params.Limit,
		params.Type,
		params.Name,
		params.Status,
	)
	response.JSON(c, gin.H{
		"list":  list,
		"count": count,
	}, err)
}

// AllCornerLabel 所有角标列表
func (g Goods) AllCornerLabel(c *gin.Context) {

	list, count, err := robot.RobotCornerLabel{}.All(
		c.Request.Context(),
	)
	response.JSON(c, gin.H{
		"list":  list,
		"count": count,
	}, err)
}

// BGBindSetting 获取背景绑定设置
func (g Goods) BGBindSetting(c *gin.Context) {
	bindSetting := robot.RobotBackground{}.GetBindSetting(c.Request.Context(), c.Query("bg_id"))
	response.JSON(c, bindSetting, nil)
}

// BindBackgroundRobots 绑定背景和机器
func (g Goods) BGBindSet(c *gin.Context) {
	var params struct {
		BGID     string `json:"bg_id"`
		RobotIDs string `json:"robot_ids"`
	}
	c.ShouldBindBodyWith(&params, binding.JSON)
	robotIDs := []string{}
	if params.RobotIDs != "" {
		robotIDs = strings.Split(params.RobotIDs, ",")
	}
	robot.RobotBackground{}.BindSet(c.Request.Context(), params.BGID, robotIDs)
	response.JSON(c, nil, nil)
}

// ListImgOfBackground 首页推荐背景图列表
func (g Goods) ListImgOfBackground(c *gin.Context) {
	var params struct {
		Page       int    `json:"page"`        // 背景图片
		Limit      int    `json:"limit"`       // 排序值
		DefaultUse int    `json:"default_use"` // 状态 1上架 2下架
		Name       string `json:"name"`        // 名称
	}
	err := c.ShouldBindWith(&params, binding.JSON)
	if err != nil {
		response.JSON(c, nil, errorx.New("参数错误", -1))
		return
	}
	list, count, err := robot.RobotBackground{}.List(
		c.Request.Context(),
		params.Page,
		params.Limit,
		params.DefaultUse,
		params.Name,
		c.GetString("merchant_id"),
	)
	response.JSON(c, gin.H{
		"list":  list,
		"count": count,
	}, err)
}

// DelImgOfBackground 删除首页推荐背景图
func (g Goods) DelImgOfBackground(c *gin.Context) {
	var params struct {
		ID string `json:"id"` // 背景图片
	}
	err := c.ShouldBindWith(&params, binding.JSON)
	if err != nil {
		response.JSON(c, nil, errorx.New("参数错误", -1))
		return
	}
	err = robot.RobotBackground{}.Del(
		c.Request.Context(),
		params.ID,
	)
	response.JSON(c, nil, err)
}

// AddGoodsImgOfBackground 新增商品首页推荐图
func (g Goods) AddImgOfBackground(c *gin.Context) {
	var params struct {
		ID         string `json:"id"`          // 更新时传ID
		Image      string `json:"image"`       // 背景图片
		DefaultUse int    `json:"default_use"` // 排序值
		Name       string `json:"name"`        // 排序值
		Position   int    `json:"position"`    // 排序值
	}
	err := c.ShouldBindWith(&params, binding.JSON)
	if err != nil {
		response.JSON(c, nil, errorx.New("参数错误", -1))
		return
	}
	err = robot.RobotBackground{}.Add(
		c.Request.Context(),
		params.ID,
		params.Image,
		params.DefaultUse,
		params.Name,
		params.Position,
		c.GetString("merchant_id"),
	)
	response.JSON(c, nil, err)
}

// set
func (g Goods) SetImgOfBackground(c *gin.Context) {
	var params struct {
		Image      string `json:"image"`       // 背景图片
		ID         string `json:"id"`          // 排序值
		DefaultUse int    `json:"default_use"` // 排序值
	}
	err := c.ShouldBindWith(&params, binding.JSON)
	if err != nil {
		response.JSON(c, nil, errorx.New("参数错误", -1))
		return
	}
	err = robot.RobotBackground{}.Set(
		c.Request.Context(),
		params.ID,
		params.DefaultUse,
	)
	response.JSON(c, nil, err)
}

// SaveGoodsInfo 新增编辑商品信息
func (g Goods) SaveGoodsInfo(c *gin.Context) {
	var params struct {
		GoodsID            string  `json:"goods_id"`             // 商品ID
		GoodsType          int     `json:"goods_type"`           // 商品类型
		GoodsName1         string  `json:"goods_name1"`          // 中文名称
		GoodsName2         string  `json:"goods_name2"`          // 英文名称
		ClassID            string  `json:"class_id"`             // 商品分类
		Price              float64 `json:"price"`                // 商品价格
		GoodsImage         string  `json:"goods_image"`          // 商品图片
		GoodsCode          string  `json:"goods_code"`           // 国际编码
		Price1             float64 `json:"price1"`               // 下划线价格
		GoodsDetail        string  `json:"goods_detail"`         // 商品详情
		GoodsVoice         string  `json:"goods_voice"`          // 商品详情
		ShowTag            string  `json:"show_tag"`             // 展示标签
		Spring             string  `json:"spring"`               // 弹簧价格
		IsAuth             int     `json:"is_auth"`              // 是否是正版授权
		ExternalProductID  string  `json:"external_product_id"`  // 外部商品id
		VoiceKeywords      string  `json:"voice_keywords"`       // 语音关键词
		DeductionLimit     float64 `json:"deduction_limit"`      // 抵扣上限
		Points             float64 `json:"points"`               // 抵扣积分
		PointsSupport      int     `json:"points_support"`       // 是否支持现金抵扣积分 0关1开
		CodeImage          string  `json:"code_image"`           // 界面引导图
		Recommend          int     `json:"recommend"`            // 是否退款 1推荐 2不推荐
		RecommendImage     string  `json:"recommend_image"`      // 商品推荐图（一张）
		AdImage            string  `json:"ad_image"`             // 商品广告推荐图（一张）
		CornerLabelID      string  `json:"corner_label_id"`      // 角标ID
		TagCode            string  `json:"tag_code"`             // 商品编码
		PurchaseType       int     `json:"purchase_type"`        // 购买配置
		ReviewPoints       int     `json:"review_points"`        // 评测积分
		ExpressFeeTemplate string  `json:"express_fee_template"` // 运费模版

		//商品导流功能
		GoodsGuideType   define.GoodsGuideType `json:"goods_guide_type"` //导流类型： QR\ShareCode
		GoodsGuideURL    string                `json:"goods_guide_url"`
		ShareCodeType    define.ShareCodeType  `json:"share_code_type"`    //口令类型，如TaoBao、JD
		ShareCode        string                `json:"share_code"`         //口令码
		GoodsGuideNotice string                `json:"goods_guide_notice"` //导流须知
	}
	err := c.ShouldBindWith(&params, binding.JSON)
	if err != nil {
		response.JSON(c, nil, errorx.New("参数错误", -1))
		return
	}

	merchantID := c.GetString("merchant_id")
	if params.GoodsType == 0 {
		params.GoodsType = c.GetInt("goods_type")
	}
	err = goods.GoodsService{}.SaveGoodsInfo(c.Request.Context(), merchantID, params.GoodsID, params.GoodsType,
		params.GoodsName1, params.GoodsName2, params.ClassID, params.Price, params.Price1, params.GoodsImage,
		params.GoodsCode, params.GoodsDetail, params.ShowTag, params.Spring, params.IsAuth,
		params.ExternalProductID, params.GoodsVoice, params.DeductionLimit, params.Points, params.PointsSupport,
		params.CodeImage, params.VoiceKeywords, params.Recommend,
		params.RecommendImage, params.AdImage, params.CornerLabelID, params.TagCode, params.PurchaseType,
		params.ReviewPoints, params.ExpressFeeTemplate,
		params.GoodsGuideType, params.GoodsGuideURL, params.ShareCodeType, params.ShareCode, params.GoodsGuideNotice,
	)
	response.JSON(c, nil, err)
}

// GoodsDetail 获取商品详情
func (g Goods) GoodsDetail(c *gin.Context) {
	var params struct {
		GoodsID string `json:"goods_id"`
	}
	err := c.ShouldBindWith(&params, binding.JSON)
	if err != nil {
		response.JSON(c, nil, errorx.New("参数错误", -1))
		return
	}

	merchantID := c.GetString("merchant_id")
	data, err := goods.GoodsService{}.GoodsDetail(c.Request.Context(), merchantID, params.GoodsID)
	response.JSON(c, data, err)
}

// 同步机器规则
func (g Goods) SyncActivityGoods(c *gin.Context) {
	var params struct {
		NowRobotName  string `json:"now_robot_name"`
		NowActivityID string `json:"now_activity_id"`
		SyncRobotName string `json:"sync_robot_name"`
	}
	err := c.ShouldBindWith(&params, binding.JSON)
	if err != nil {
		response.JSON(c, nil, errorx.New("参数错误", -1))
		return
	}
	// 开始请求同步服务
	data, AsyncCount, err := goods.GoodsService{}.SyncActivityGoods(c.Request.Context(), c.GetString("merchant_id"),
		params.NowRobotName,  // 当前机器
		params.NowActivityID, // 当前活动ID
		params.SyncRobotName, // 需要同步的机器
	)
	response.JSON(c, gin.H{
		"data":  data,
		"count": AsyncCount,
	}, err)
	// response.JSON(c, AsyncCount, err)
}

// list
func (g Goods) ActivityGoodsList(c *gin.Context) {
	var params struct {
		SalesID string `json:"sales_id"`
	}
	err := c.ShouldBindWith(&params, binding.JSON)
	if err != nil {
		response.JSON(c, nil, errorx.New("参数错误", -1))
		return
	}
	merchantID := c.GetString("merchant_id")
	data, err := goods.GoodsService{}.GetActivityGoodsOfMulti(
		c.Request.Context(),
		merchantID,
		params.SalesID,
		"",
	)

	sort.Slice(data, func(i, j int) bool {
		return data[i].ID < data[j].ID
	})

	response.JSON(c, data, err)
}

// 获取活动商品
func (g Goods) GetActivityGoods(c *gin.Context) {
	var params struct {
		SalesID string `json:"sales_id"`
		ID      string `json:"activity_id"`
	}
	err := c.ShouldBindWith(&params, binding.JSON)
	if err != nil {
		response.JSON(c, nil, errorx.New("参数错误", -1))
		return
	}
	merchantID := c.GetString("merchant_id")
	// 需要实现过滤 -- 关联商品和优惠商品
	data, err := goods.GoodsService{}.GetActivityGoodsOfMulti(
		c.Request.Context(),
		merchantID,
		params.SalesID,
		params.ID, // 活动ID
	)

	if err != nil {
		response.JSON(c, err, errorx.New("获取失败", -1))
		return
	}
	var mydata schema.AllGoodsActivityDataDetail
	if len(data) > 0 {
		mydata = data[0]
		response.JSON(c, mydata, err)
	} else {
		response.JSON(c, "", err)
	}

}

// 删除活动商品
func (g Goods) DelActivityGoods(c *gin.Context) {
	var params struct {
		SalesID    string `json:"sales_id"`
		ActivityID string `json:"activity_id"`
	}
	err := c.ShouldBindWith(&params, binding.JSON)
	if err != nil {
		response.JSON(c, nil, errorx.New("参数错误", -1))
		return
	}
	merchantID := c.GetString("merchant_id")
	err = goods.GoodsService{}.DelActivityGoodsOfMulti(
		c.Request.Context(),
		merchantID,
		params.ActivityID,
		params.SalesID,
	)
	response.JSON(c, nil, err)
}

// 新增、编辑活动商品
func (g Goods) SetActivityGoods(c *gin.Context) {
	var params struct {
		Name      string                     `json:"name"`
		SalesID   string                     `json:"sales_id"`
		StartTime string                     `json:"start_time"`
		EndTime   string                     `json:"end_time"`
		Data      []schema.GoodsActivityData `json:"data"`
		ID        string                     `json:"activity_id"`
	}
	err := c.ShouldBindWith(&params, binding.JSON)
	if err != nil {
		response.JSON(c, nil, errorx.New("参数错误", -1))
		return
	}
	merchantID := c.GetString("merchant_id")
	err = goods.GoodsService{}.SaveActivityGoodsOfMulti(
		c.Request.Context(),
		merchantID,
		params.Name,
		params.SalesID,
		params.StartTime,
		params.EndTime,
		params.ID,
		params.Data,
	)
	response.JSON(c, nil, err)
}

// AddGoodsOfMulti 新增多规格商品
func (g Goods) AddGoodsOfMulti(c *gin.Context) {
	var params struct {
		ID          string                 `json:"id"`
		GoodsName   string                 `json:"goods_name"`
		MultiGoods  []schema.MultiGoodsNew `json:"multi_goods"`
		GoodsDetail string                 `json:"goods_detail"`
		SalesID     string                 `json:"sales_id"`
		RobotName   string                 `json:"robot_name"`
	}
	err := c.ShouldBindWith(&params, binding.JSON)
	if err != nil {
		response.JSON(c, nil, errorx.New("参数错误", -1))
		return
	}

	merchantID := c.GetString("merchant_id")
	err = goods.GoodsService{}.SaveGoodsOfMulti(c.Request.Context(), merchantID, params.ID,
		params.GoodsName, params.MultiGoods, params.GoodsDetail, params.SalesID, params.RobotName)
	response.JSON(c, nil, err)
}

// EditGoodsOfMulti 编辑多规格商品
func (g Goods) EditGoodsOfMulti(c *gin.Context) {
	var params struct {
		ID          string                 `json:"id"`
		GoodsName   string                 `json:"goods_name"`
		MultiGoods  []schema.MultiGoodsNew `json:"multi_goods"`
		GoodsDetail string                 `json:"goods_detail"`
		SalesID     string                 `json:"sales_id"`
		RobotName   string                 `json:"robot_name"`
	}
	err := c.ShouldBindWith(&params, binding.JSON)
	if err != nil {
		response.JSON(c, nil, errorx.New("参数错误", -1))
		return
	}

	merchantID := c.GetString("merchant_id")
	err = goods.GoodsService{}.SaveGoodsOfMulti(c.Request.Context(), merchantID, params.ID,
		params.GoodsName, params.MultiGoods, params.GoodsDetail, params.SalesID, params.RobotName)
	response.JSON(c, nil, err)
}

// DelGoodsOfMulti 删除多规格商品
func (g Goods) DelGoodsOfMulti(c *gin.Context) {
	var params struct {
		ID string `json:"id"`
	}
	err := c.ShouldBindWith(&params, binding.JSON)
	if err != nil {
		response.JSON(c, nil, errorx.New("参数错误", -1))
		return
	}

	err = goods.GoodsService{}.DelGoodsOfMulti(c.Request.Context(), params.ID)
	response.JSON(c, nil, err)
}

// DetailGoodsOfMulti 多规格商品详情
func (g Goods) DetailGoodsOfMulti(c *gin.Context) {
	var params struct {
		ID string `json:"id"`
	}
	err := c.ShouldBindWith(&params, binding.JSON)
	if err != nil {
		response.JSON(c, nil, errorx.New("参数错误", -1))
		return
	}

	data, err := goods.GoodsService{}.DetailGoodsOfMulti(c.Request.Context(), params.ID)
	response.JSON(c, data, err)
}

// List 获取商品列表
func (g Goods) List(c *gin.Context) {
	var params struct {
		ClassID     string    `json:"class_id"`
		GoodsName   string    `json:"goods_name"`
		GoodsStatus *int      `json:"goods_status"`
		ShopID      *[]string `json:"shop_id"`
		GoodsType   int       `json:"goods_type"`
		Page        int       `json:"page"`
		Limit       int       `json:"limit"`
	}
	err := c.ShouldBindWith(&params, binding.JSON)
	if err != nil {
		response.JSON(c, nil, errorx.New("参数错误", -1))
		return
	}

	merchantID := c.GetString("merchant_id")
	var shopIDList = []string{}
	if params.ShopID != nil {
		shopIDList = append(shopIDList, *params.ShopID...)
	}
	data, count, err := goods.GoodsService{}.List(c.Request.Context(), merchantID, shopIDList,
		params.ClassID, params.GoodsName, params.GoodsStatus, params.GoodsType,
		params.Page, params.Limit)
	response.JSON(c, gin.H{
		"data":  data,
		"count": count,
	}, err)
}

// Options 获取商品列表
func (g Goods) Options(c *gin.Context) {
	var params struct {
		ProvinceID string    `json:"province_id"` // 省份id,多选
		CityID     string    `json:"city_id"`     // 城市id,多选
		DistrictID string    `json:"district_id"` // 区县id,多选
		LocationID string    `json:"location_id"` // 位置id,多选
		ShopID     *[]string `json:"shop_id"`     // 归属商户
		RobotID    string    `json:"robot_id"`    // 设备名称
		GoodsName  string    `json:"goods_name"`  // 商品名称
		Page       int       `json:"page"`
		Limit      int       `json:"limit"`
	}
	err := c.ShouldBindWith(&params, binding.JSON)
	if err != nil {
		response.JSON(c, nil, errorx.New("参数错误", -1))
		return
	}

	merchantID := c.GetString("merchant_id")
	var shopIDList = []string{}
	if params.ShopID != nil {
		shopIDList = append(shopIDList, *params.ShopID...)
	}
	data, count, err := goods.GoodsService{}.Options(c.Request.Context(), merchantID, shopIDList,
		params.ProvinceID, params.CityID, params.DistrictID, params.LocationID, params.RobotID,
		params.GoodsName, params.Page, params.Limit)
	response.JSON(c, gin.H{
		"data":  data,
		"count": count,
	}, err)
}

// Remove 商品删除
func (g Goods) Remove(c *gin.Context) {
	var params struct {
		GoodsIDList string `json:"goods_id_list"`
	}
	err := c.ShouldBindWith(&params, binding.JSON)
	if err != nil {
		response.JSON(c, nil, errorx.New("参数错误", -1))
		return
	}

	merchantID := c.GetString("merchant_id")
	err = goods.GoodsService{}.Remove(c.Request.Context(), merchantID, params.GoodsIDList)
	response.JSON(c, nil, err)
}

// Set 商品上下架
func (g Goods) Set(c *gin.Context) {
	var params struct {
		GoodsID     string `json:"goods_id"`
		GoodsStatus int    `json:"goods_status"`
	}
	err := c.ShouldBindWith(&params, binding.JSON)
	if err != nil {
		response.JSON(c, nil, errorx.New("参数错误", -1))
		return
	}
	merchantID := c.GetString("merchant_id")
	err = goods.GoodsService{}.Set(c.Request.Context(), merchantID, params.GoodsID, params.GoodsStatus)
	response.JSON(c, nil, err)
}

// RobotGoodsOffShelf 商品下架
func (g Goods) RobotGoodsOffShelf(c *gin.Context) {
	// 获取请求参数
	var params struct {
		GoodsID string `json:"goods_id"` // 商品id
		RobotID string `json:"robot_id"` // 机器id，多个以逗号分隔
	}
	err := c.ShouldBindWith(&params, binding.JSON)
	if err != nil {
		response.JSON(c, nil, errorx.New("参数错误", -1))
		return
	}
	// 获取操作者的商户id
	merchantID := c.GetString("merchant_id")
	// 下架的机器
	robotIDs := []string{}
	if params.RobotID != "" {
		robotIDs = strings.Split(params.RobotID, ",")
	}
	// 下架机器的商品
	err = goods.GoodsService{}.RobotGoodsOffShelf(c.Request.Context(), merchantID,
		params.GoodsID,
		robotIDs,
	)
	response.JSON(c, nil, err)
}

// RecommendedGoodsOffShelf 首页推荐产品下架
func (g Goods) RobotRecommendedGoodsOffShelf(c *gin.Context) {
	// 获取请求参数
	var params struct {
		GoodsID string `json:"goods_id"` // 商品id
		RobotID string `json:"robot_id"` // 机器id，多个以逗号分隔
	}
	err := c.ShouldBindWith(&params, binding.JSON)
	if err != nil {
		response.JSON(c, nil, errorx.New("参数错误", -1))
		return
	}
	// 操作者的商户id
	merchantID := c.GetString("merchant_id")
	// 下架的机器
	robotIDs := []string{}
	if params.RobotID != "" {
		robotIDs = strings.Split(params.RobotID, ",")
	}
	// 下架机器的推荐商品
	err = goods.GoodsService{}.RobotRecommendedGoodsOffShelf(c.Request.Context(), merchantID,
		params.GoodsID,
		robotIDs,
	)
	response.JSON(c, nil, err)
}

// RobotGoodsADOffShelf 广告商品下架
func (g Goods) RobotGoodsADOffShelf(c *gin.Context) {
	var params struct {
		GoodsID string `json:"goods_id"` // 商品id
		RobotID string `json:"robot_id"` // 机器id，多个以逗号分隔
	}
	err := c.ShouldBindWith(&params, binding.JSON)
	if err != nil {
		response.JSON(c, nil, errorx.New("参数错误", -1))
		return
	}
	// 获取操作者的商户id
	merchantID := c.GetString("merchant_id")
	// 下架的机器
	robotIDs := []string{}
	if params.RobotID != "" {
		robotIDs = strings.Split(params.RobotID, ",")
	}
	// 下架机器的商品广告
	err = goods.GoodsService{}.RobotGoodsADOffShelf(c.Request.Context(), merchantID,
		params.GoodsID,
		robotIDs,
	)
	response.JSON(c, nil, err)
}

// LogList 查询商品变更记录
func (g Goods) LogList(c *gin.Context) {
	var params struct {
		SalesID    string `json:"sales_id"`
		ActivityID string `json:"activity_id"`
	}
	err := c.ShouldBindWith(&params, binding.JSON)
	if err != nil {
		response.JSON(c, nil, errorx.New("参数错误", -1))
		return
	}
	merchantID := c.GetString("merchant_id")
	err = goods.GoodsService{}.DelActivityGoodsOfMulti(
		c.Request.Context(),
		merchantID,
		params.ActivityID,
		params.SalesID,
	)
	response.JSON(c, nil, err)
}

// LogList 查询商品变更明细
func (g Goods) LogDetail(c *gin.Context) {
	//var params struct {
	//	ID string `json:"id"`
	//}
	//err := c.ShouldBindWith(&params, binding.JSON)
	//if err != nil {
	//	response.JSON(c, nil, errorx.New("参数错误", -1))
	//	return
	//}
	logID := c.GetInt64("log_id")
	err := goods.GoodsService{}.LogDetail(
		c.Request.Context(),
		logID,
	)
	response.JSON(c, nil, err)
}
